<?php

namespace app\spare\controller;

use cmf\controller\HomeBaseController;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class IndexController extends HomeBaseController
{
    /**
     * 备用金首页
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function index()
    {
        $data = Db::name('spare')->order('date desc')->select()->toArray();
        foreach ($data as $k => $v) {
            $data[$k]['engine'] = Db::name('engine')->where(['id' => $v['reim']])->value('name');
            $data[$k]['payee'] = Db::name('staff')->where(['id' => $v['payee']])->value('name');
        }
        $all = Db::name('spare')->sum('price');
        $sums = Db::name('run_bill')->where(['payfor'=>1])->sum('count') + Db::name('life')->where(['status' => 1])->sum('price');
        $expen = Db::name('expen')->where(['type'=>1])->sum('nums*price');
        $pec = Db::name('spare')->group('reim')->field('reim')->select()->toArray();
        foreach ($pec as $k => $v) {
            $pec[$k]['name'] = Db::name('engine')->where(['id' => $v['reim']])->value('name');
            $pec[$k]['price'] = Db::name('spare')->where(['reim' => $v['reim']])->sum('price');
            $pec[$k]['back'] = Db::name('run_bill')->where(['eid' => $v['reim'], 'payfor' => 1])->sum('count');
            $pec[$k]['life'] = Db::name('life')->where(['eid' => $v['reim'], 'status' => 1])->sum('price');
            $pec[$k]['brance'] = $pec[$k]['price'] - $pec[$k]['back'] - $pec[$k]['life'];
        }
        $this->assign('expen',$expen);
        $this->assign('sums', $sums);
        $this->assign('data', $data);
        $this->assign('all', $all);
        $this->assign('pec', $pec);
        return $this->fetch();
    }

    /**
     * 新增备用金款项
     * @return mixed|string
     */
    public function add()
    {
        $role = Db::name('role_user')->where(['user_id' => cmf_get_current_admin_id()])->value('role_id');
        if ($role == 2) {
            $this->error('无权限操作');
        }
        $data = Db::name('engine')->field('id,name')->select();
        $user = Db::name('staff')->field('id,name')->select();
        $this->assign('user', $user);
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function doadd()
    {
        $data = $this->request->param();
        if (empty($data['date']) || empty($data['pay']) || empty($data['payee']) || empty($data['desc']) || empty($data['unit']) || empty($data['price']) || empty($data['reim']) || empty($data['title'])) {
            $this->error('请填写完整');
        }
        $files = $this->request->file('imgs');
        unset($data['imgs']);
        if ($files) {
            $kps = [];
            foreach ($files as $k => $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
                if ($info) {
                    $kps[$k] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
                } else {
                    $this->error($file->getError());
                }
            }
            $data['imgs'] = implode(',', $kps);
        }
        $res = Db::name('spare')->insert($data);
        if (!$res) {
            $img = explode(',', $data['imgs']);
            foreach ($img as $k => $v) {
                $v = CMF_ROOT . $v;
                if ($v != CMF_ROOT && file_exists($v)) {
                    unlink($v);
                }
            }
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    public function edit()
    {
        $data = $this->request->param();
        $en = Db::name('engine')->field('id,name')->select();

        $res = Db::name('spare')->where(['id' => $data['id']])->find();
        $res['imgs'] = explode(',', $res['imgs']);
        foreach ($res['imgs'] as $k => &$v) {
            $v = 'http://' . $_SERVER['SERVER_NAME'] . $v;
        }
        $res['payeename'] = Db::name('staff')->where(['id' => $res['payee']])->value('name');
        $res['reimName'] = Db::name('engine')->where(['id' => $res['reim']])->value('name');
        $data = Db::name('engine')->field('id,name')->select();
        $user = Db::name('staff')->field('id,name')->select();
        $this->assign('en', $en);
        $this->assign('res', $res);
        $this->assign('data', $data);
        $this->assign('user', $user);
        return $this->fetch();
    }

    public function doedit()
    {
        $role = Db::name('role_user')->where(['user_id' => cmf_get_current_admin_id()])->value('role_id');
        if ($role == 2) {
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $files = $this->request->file('imgs');
        $check = Db::name('spare')->where(['id' => $data['id']])->find();
        $id = $data['id'];
        $uper = [
            'date' => $data['date'],
            'pay' => $data['pay'],
            'payee' => $data['payee'],
            'desc' => $data['desc'],
            'unit' => $data['unit'],
            'price' => $data['price'],
            'reim' => $data['reim'],
            'title' => $data['title']
        ];
        if ($files) {
            $kps = [];
            foreach ($files as $k => $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
                if ($info) {
                    $kps[$k] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
                } else {
                    $this->error($file->getError());
                }
            }
            $uper['imgs'] = implode(',', $kps);
            if ($check['imgs']) {
                $img = explode(',', $check['imgs']);
                foreach ($img as $k => $v) {
                    $v = CMF_ROOT . $v;
                    if ($v != CMF_ROOT && file_exists($v)) {
                        unlink($v);
                    }
                }
            }
        }
        $res = Db::name('spare')->where(['id' => $id])->update($uper);
        if (!$res) {
            if ($check['imgs']) {
                $pic = explode(',', $check['imgs']);
                foreach ($pic as $k => $v) {
                    $v = CMF_ROOT . $v;
                    if ($v != CMF_ROOT && file_exists($v)) {
                        unlink($v);
                    }
                }
            }

            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    public function del()
    {
        $role = Db::name('role_user')->where(['user_id' => cmf_get_current_admin_id()])->value('role_id');
        if ($role == 2) {
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $check = Db::name('spare')->where(['id' => $data['id']])->find();
        $img = explode(',', $check['imgs']);
        foreach ($img as $k => $v) {
            $v = CMF_ROOT . $v;
            if ($v != CMF_ROOT && file_exists($v)) {
                unlink($v);
            }
        }
        $res = Db::name('spare')->where(['id' => $data['id']])->delete();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
}